<template>
    <div class="form-page">
        <el-form
            ref="form"
            :model="form"
            :rules="formRules"
            :inline="true"
            label-width="8em"
            class="data-form"
        >
            <div class="form-item">
                <div class="title">基础信息</div>
                <div class="yx-start al-start data">
                    <el-form-item prop="name" label="姓名（昵称）">
                        <el-input v-model="form.name"></el-input>
                    </el-form-item>
                    <el-form-item prop="mobile" label="手机号">
                        <el-input
                            v-model="form.mobile"
                            :disabled="edit"
                        ></el-input>
                    </el-form-item>



                    <el-form-item prop="roleIds" label="菜单角色">
                        <el-select
                            :disabled="isDisabled"
                            v-model="form.roleIds"
                            v-loading="flag.searchRolesFlag"
                            multiple
                            filterable
                            remote
                            reserve-keyword
                            placeholder="请输入关键词"
                            :remote-method="searchRoles"
                        >
                            <el-option
                                v-for="item in rolesList"
                                :key="item.id"
                                :label="item.name"
                                :value="item.id"
                            >
                            </el-option>
                        </el-select>
                    </el-form-item>

                </div>
            </div>
            <div v-if="addAction" class="form-item xy-start al-str">
                <div class="title">登录信息</div>
                <div class="yx-start al-start data">
                    <el-form-item prop="password" label="密码">
                        <el-input
                            v-model="form.password"
                            type="password"
                        ></el-input>
                    </el-form-item>
                    <el-form-item prop="checkPass" label="确认密码">
                        <el-input
                            v-model="form.checkPass"
                            type="password"
                        ></el-input>
                    </el-form-item>
                </div>
            </div>

            <div class="form-item xy-start al-str" v-if="!form.parentId&&(state===null ||state===undefined)">
                <div class="title">扩展设置</div>

                <div class="yx-start al-start data">
                    <el-form-item label="代理商类型">
                        <el-select
                            v-model="form.agentType"
                            filterable
                            clearable
                            placeholder="请选择"
                        >
                            <el-option v-for="(label, value) in agentType" :key="value" :label="label"  :value="value">

                            </el-option>

                        </el-select>
                    </el-form-item>

                    <el-form-item v-if="!form.parentId" prop="levelId" label="代理商级别">
                        <el-cascader
                            ref="levelRef"
                            v-model="form.levelId"
                            v-loading="flag.levelFlag"
                            :options="levelList"
                            placeholder="请输入关键词"
                            :show-all-levels="false"
                            clearable
                            filterable
                            :before-filter="searchLevel"
                            :props="{
                                value: 'id',
                                label: 'name',
                                emitPath: false,
                                checkStrictly: true
                            }"
                        >
                        </el-cascader>
                    </el-form-item>
                </div>
            </div>
        </el-form>
        <div ref="submitDiv" class="form-item xy-center from-operation">
            <el-button
                type="primary"
                icon="el-icon-folder"
                :loading="submitFlag"
                @click="save"
            >保存
            </el-button
            >
            <el-button
                type="warning"
                icon="el-icon-delete-solid"
                :loading="submitFlag"
                @click="()=> {this.$store.dispatch('tagsView/delView', this.$route);this.$router.go(-1);}"
            >取消
            </el-button
            >
        </div>
    </div>
</template>

<script>
import {FormPage} from "@/layout/mixin/iVue.js";
import {mapState} from "vuex";
import {
    fetchPositionList,
    fetchRoleList,
    checkUsernameExits,
    checkMobileExits,
    fetchUserSimpleDetail, fetchAgentLevelList, fetchRoleAnyList
} from "@/api/user.js";
import {isMobile} from "@/utils/validate.js";
import {ossUpload} from "@/utils/file.js";
import {treeList2Tree, beanCopy} from "@/utils/index.js";
import AriaUtils from "element-ui/src/utils/aria-utils";
import {get, put, post} from "@/api/request";

const {keys: KeyCode} = AriaUtils;
export default {
    name: "AgentUserAdd",
    components: {},
    mixins: [FormPage],
    data() {
        return {
            form: {
                id: null,
                name: null,
                mobile: null,
                sex: null,
                header: null,
                positionCode: null,
                username: null,
                password: null,
                checkPass: null,
                parentId: null,
                positionCodes: null,
                roleIds: null,
                agentId: null,
                agentType: null,
                parent: {
                    name: ""
                },
            },
            isDisabled:false,
            levelList: null,
            refresh: false,
            agentList: null,
            base64Header: null,
            positionList: null,
            parentPositionList: null,
            rolesList: null,
            parents: null,
            state: null,
            parent: {
                positionId: null
            },
            formRules: {
                name: [
                    {
                        required: true,
                        message: "请输入姓名",
                        trigger: "blur"
                    },
                    {
                        min: 2,
                        max: 10,
                        message: "长度在 2 到 10 个字符",
                        trigger: "blur"
                    }
                ],
                agentId: [
                    {
                        required: true,
                        message: "请选择代理商",
                        trigger: "change"
                    }
                ],
                username: [
                    {
                        required: true,
                        message: "请输入登录用户名",
                        trigger: "blur"
                    },
                    {
                        validator: (rule, value, callback) => {
                            if (!this.addAction) {
                                callback();
                            }
                            if (value) {
                                checkUsernameExits({
                                    username: value,
                                    userType: "agent"
                                }).then(res => {
                                    if (res) {
                                        callback(new Error("用户名已经存在"));
                                    } else {
                                        callback();
                                    }
                                });
                            }
                        },
                        trigger: "blur"
                    }
                ],
                password: [
                    {
                        required: true,
                        message: "请输入密码",
                        trigger: "blur"
                    },
                    {
                        min: 6,
                        max: 20,
                        message: "长度在 6 到 20 个字符",
                        trigger: "blur"
                    }
                ],
                checkPass: [
                    {
                        required: true,
                        message: "请再次输入密码",
                        trigger: "blur"
                    },
                    {
                        validator: (rule, value, callback) => {
                            if (value !== this.form.password) {
                                callback(new Error("两次输入密码不一致!"));
                            } else {
                                callback();
                            }
                        },
                        trigger: "blur"
                    }
                ],
                mobile: [
                    {
                        required: true,
                        message: "请输入手机号",
                        trigger: "blur"
                    },
                    {
                        validator: (rule, value, callback) => {
                            if (!this.addAction) {
                                callback();
                            }
                            if (value) {
                                if (isMobile(value)) {
                                    checkMobileExits({
                                        mobile: value,
                                        userType: "agent"
                                    }).then(res => {
                                        if (res) {
                                            callback(
                                                new Error("手机号已被使用")
                                            );
                                        } else {
                                            callback();
                                        }
                                    });
                                } else {
                                    callback(new Error("请输入正确的手机号"));
                                }
                            }
                        },
                        trigger: "blur"
                    }
                ]
            },
            flag: {
                positionListFlag: false,
                searchRolesFlag: false,
                agentFlag: false,
                levelFlag:false,
            }
        };
    },
    computed: {
        ...mapState({
            currentUser: state => state.currentUser,
            userInfo: state => state.currentUser,
            agentType: state => state.status.agentType,
        })
    },
    watch: {},
    mounted() {
    },
    created() {
        this.refresh = this.$route.query.refresh;
        this.state = this.$route.query.flag;
        this.isDisabled = !super.haveRole("agentManage:edit")
        console.log( "isdisabled",this.isDisabled);
        if (!this.$route.query.id) {
            if (this.$route.query.pid) {
                this.form.parentId = this.$route.query.pid;
                this.form.positionCodes = ["agentKefu"];
                this.form.roleIds = ["agentKefu"];
                // fetchUserSimpleDetail({id: this.form.parentId}).then(res => this.form.parent = res);
            } else {
                this.form.positionCodes = ["agentAdmin"];
                this.form.roleIds = ["agentAdmin"];
            }
        }

    },
    methods: {
        async loadData(id) {
            return Promise.all([
                this.loadUserOld(id),
                this.searchPosition(),
                this.searchRoles(),
                this.searchLevel()
            ]).catch(e => {
                this.$message.error("数据加载失败，请稍后在试");
            });
        },
        async loadUserOld(id) {
            if (!id) {
                // this.form.createdByName = this.currentUser.name;
                // this.form.createdBy = this.currentUser.id
                return;
            }
            get(`/user/cu/agent/user/edit/detail/${id}`, {showParent: false}).then(result => {
                beanCopy(result, this.form, true);
                // this.form=result;
                this.form.positionCodes = result.positions.map(v => v.code);
                this.form.roleIds = result.roles.map(v => v.id);
            });
        },
        searchPosition(query) {
            return this.flagPromise(
                fetchPositionList({
                    name: query,
                    size: 100
                }).then(data => {
                    if (data.length === 0 && query) {
                        this.searchPosition();
                    } else {
                        this.positionList = treeList2Tree(data);
                    }
                }),
                "positionListFlag"
            );
        },
        searchRoles(query) {

            // eslint-disable-next-line no-unreachable
            if(this.userInfo.userTypes.includes("channelBusiness")){
                return this.flagPromise(
                    fetchRoleAnyList({
                        showLevel: "CHANNEL",
                    }).then(data => {
                        this.rolesList = data;
                    }),
                    "searchRolesFlag"
                );
            }else{
                return this.flagPromise(
                    fetchRoleList({
                        name: query,
                        size: 100
                    }).then(data => {
                        this.rolesList = data;
                    }),
                    "searchRolesFlag"
                );
            }
        },

        searchLevel(query) {
            return this.flagPromise(
                fetchAgentLevelList({
                    size: 1000
                }).then(data => {
                    this.levelList = data;
                }),
                "levelFlag"
            );
        },
        save() {
            this.form.banance = null;
            this.form.accumulativeRecharge = null;
            this.form.cumulativeConsumption = null;
            let backURL = "agentUser?refresh=true";
            if (this.refresh) {
                backURL = this.refresh;
            }
            //避免修改金额
            if (this.addAction) {
                this.clickSave(
                    "/user/cu/agent/user/edit/add",
                    this.form,
                    false,
                ).then(res => {

                    this.$router.go(-1)
                });

            } else {
                this.clickSave(
                    "/user/cu/agent/user/edit/update",
                    this.form,
                    true,
                ).then(res => {

                    this.$router.go(-1)
                });
            }

        },
        headerChange(file, fileList) {
            if (fileList.length > 1) {
                fileList.splice(0, 1);
            }
            const elFile = fileList[0];
            file = fileList[0].raw;
            let imgReaderl = new FileReader();
            imgReaderl.onload = evt => {
                this.base64Header = evt.target.result;
            };
            imgReaderl.readAsDataURL(file);
            ossUpload("cdn", file.name, file, p => {
                elFile.percentage = p * 100;
                elFile.status = "uploading";
            }).then(result => {
                this.form.header = result;
                elFile.status = "done";
            });
        }
    }
};
</script>

<style lang="css">
.header .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}

.header .avatar-uploader .el-upload:hover {
    border-color: #409eff;
}

.header .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 4.58rem;
    height: 4.58rem;
    line-height: 4.58rem;
    text-align: center;
}

.header .avatar {
    width: 4.58rem;
    height: 4.58rem;
    display: block;
}
</style>
